import { createSlice, createAsyncThunk, PayloadAction } from '@reduxjs/toolkit';
import { Document } from '../../types/document';
import { documentApi } from '../../api/document';

// 状态类型
interface DocumentState {
  documents: Document[];
  currentDocument: Document | null;
  loading: boolean;
  error: string | null;
  uploadProgress: number;
}

// 初始状态
const initialState: DocumentState = {
  documents: [],
  currentDocument: null,
  loading: false,
  error: null,
  uploadProgress: 0,
};

// 异步Thunk - 获取所有文档
export const fetchDocuments = createAsyncThunk(
  'document/fetchAll',
  async (_, { rejectWithValue }) => {
    try {
      return await documentApi.getAll();
    } catch (error) {
      return rejectWithValue('获取文档列表失败');
    }
  }
);

// 异步Thunk - 通过知识库ID获取文档
export const fetchDocumentsByKnowledgeBaseId = createAsyncThunk(
  'document/fetchByKnowledgeBaseId',
  async (knowledgeBaseId: number, { rejectWithValue }) => {
    try {
      return await documentApi.getByKnowledgeBaseId(knowledgeBaseId);
    } catch (error) {
      return rejectWithValue('获取知识库文档失败');
    }
  }
);

// 异步Thunk - 获取单个文档
export const fetchDocumentById = createAsyncThunk(
  'document/fetchById',
  async (id: number, { rejectWithValue }) => {
    try {
      return await documentApi.getById(id);
    } catch (error) {
      return rejectWithValue('获取文档详情失败');
    }
  }
);

// 异步Thunk - 上传文档
export const uploadDocument = createAsyncThunk(
  'document/upload',
  async ({ file, knowledgeBaseId }: { file: File; knowledgeBaseId: number }, { rejectWithValue }) => {
    try {
      return await documentApi.upload(file, knowledgeBaseId);
    } catch (error) {
      return rejectWithValue('上传文档失败');
    }
  }
);

// 文档状态切片
const documentSlice = createSlice({
  name: 'document',
  initialState,
  reducers: {
    clearCurrentDocument: (state) => {
      state.currentDocument = null;
    },
    clearError: (state) => {
      state.error = null;
    },
    setUploadProgress: (state, action: PayloadAction<number>) => {
      state.uploadProgress = action.payload;
    },
  },
  extraReducers: (builder) => {
    // 获取所有文档
    builder
      .addCase(fetchDocuments.pending, (state) => {
        state.loading = true;
        state.error = null;
      })
      .addCase(fetchDocuments.fulfilled, (state, action: PayloadAction<Document[]>) => {
        state.loading = false;
        state.documents = action.payload;
      })
      .addCase(fetchDocuments.rejected, (state, action) => {
        state.loading = false;
        state.error = action.payload as string;
      });

    // 通过知识库ID获取文档
    builder
      .addCase(fetchDocumentsByKnowledgeBaseId.pending, (state) => {
        state.loading = true;
        state.error = null;
      })
      .addCase(fetchDocumentsByKnowledgeBaseId.fulfilled, (state, action: PayloadAction<Document[]>) => {
        state.loading = false;
        state.documents = action.payload;
      })
      .addCase(fetchDocumentsByKnowledgeBaseId.rejected, (state, action) => {
        state.loading = false;
        state.error = action.payload as string;
      });

    // 获取单个文档
    builder
      .addCase(fetchDocumentById.pending, (state) => {
        state.loading = true;
        state.error = null;
      })
      .addCase(fetchDocumentById.fulfilled, (state, action: PayloadAction<Document>) => {
        state.loading = false;
        state.currentDocument = action.payload;
      })
      .addCase(fetchDocumentById.rejected, (state, action) => {
        state.loading = false;
        state.error = action.payload as string;
      });

    // 上传文档
    builder
      .addCase(uploadDocument.pending, (state) => {
        state.loading = true;
        state.error = null;
        state.uploadProgress = 0;
      })
      .addCase(uploadDocument.fulfilled, (state, action: PayloadAction<Document>) => {
        state.loading = false;
        state.documents.push(action.payload);
        state.currentDocument = action.payload;
        state.uploadProgress = 100;
      })
      .addCase(uploadDocument.rejected, (state, action) => {
        state.loading = false;
        state.error = action.payload as string;
        state.uploadProgress = 0;
      });
  },
});

export const { clearCurrentDocument, clearError, setUploadProgress } = documentSlice.actions;
export default documentSlice.reducer; 